package com.atguigu.springsecurity.config;

import com.atguigu.springsecurity.coutom.PasswordMd5;
import com.atguigu.springsecurity.filter.TokenAuthenticationFilter;
import com.atguigu.springsecurity.filter.TokenLoginFilter;
import com.atguigu.springsecurity.handler.AccessDeniedHandlerImpl;
import com.atguigu.springsecurity.handler.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@EnableGlobalMethodSecurity(prePostEnabled = true) //开启注解功能，默认禁用注解
@Configuration
//@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private TokenLoginFilter tokenLoginFilter;

    @Autowired
    private UserDetailsService userDetailsService;

    // 授权失败异常处理器
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    // 认证失败异常处理器
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    // 进行暴露
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 使用我们的md5盐值加密， 加入后springsecurity会自动替换原本的加密方法
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf()
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/admin/system/index/login").anonymous()
                // 配置权限的在配置类里面也可以写前面是访问的路径
//                .antMatchers("/testCors").hasAuthority("system:dept:list222")
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 配置异常处理器
        http.exceptionHandling().
                // 认证失败处理器
                        authenticationEntryPoint(authenticationEntryPoint).
                // 授权失败处理器
                        accessDeniedHandler(accessDeniedHandler);

        http.addFilterBefore(tokenLoginFilter, UsernamePasswordAuthenticationFilter.class);
        //禁用session
        // spring security允许跨域
        http.cors();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 指定UserDetailService和加密器
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }


    /**
     * 配置哪些请求不拦截
     * 排除swagger相关请求
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/favicon.ico", "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html");
    }


}